package com.kakahair.plat.service.impl;

import com.kakahair.common.service.impl.BaseServiceImpl;
import com.kakahair.common.util.CommonUtil;
import com.kakahair.common.util.HttpUtil;
import com.kakahair.common.util.KakahairConst;
import com.kakahair.common.util.TimeUtils;
import com.kakahair.common.util.Utility;
import com.kakahair.plat.entity.Bservice;
import com.kakahair.plat.entity.Order;
import com.kakahair.plat.entity.PayInfo;
import com.kakahair.plat.entity.Shop;
import com.kakahair.plat.entity.User;
import com.kakahair.plat.mapper.OrderMapper;
import com.kakahair.plat.service.BserviceService;
import com.kakahair.plat.service.OrderService;
import com.kakahair.plat.service.ShopService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.order.WxPayAppOrderResult;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 * 
 * @author Tiddar
 * @since 2018-04-07
 */
@Service
public class OrderServiceImpl extends BaseServiceImpl<OrderMapper, Order> implements OrderService {

	@Autowired
	ShopService shopService;
	@Autowired
	BserviceService bservice;
	@Autowired
	WxPayConfig config;

	/**
	 * <p>
	 * Title: getOrderNum
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param userId
	 * @return
	 * @see com.kakahair.plat.service.OrderService#getOrderNum(com.kakahair.plat.entity.User)
	 */
	@Override
	public Map<String, Integer> getOrderNum(String userOpenId) {
		Integer useNum = this.selectCount(
				new EntityWrapper<Order>().where("userId={0}", userOpenId).and("hasDelete=0").and("used=0"));
		Integer evaluateNum = this.selectCount(new EntityWrapper<Order>().where("userId={0}", userOpenId)
				.and("hasDelete=0").and("evaluate=0").and("used=1"));
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("use", useNum);
		map.put("evaluate", evaluateNum);
		return map;

	}

	public Order detail(Order order) {
		List<Bservice> services = bservice.selectList(new EntityWrapper<Bservice>().in("id", order.getServicesId()));
		return order.setService(services);
	}

	/**
	 * <p>
	 * Title: getOrderList
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param queryContition
	 * @param userOpenId
	 * @return
	 * @see com.kakahair.plat.service.OrderService#getOrderList(java.lang.String,
	 *      java.lang.String)
	 */
	@Override
	public List<Order> getOrderList(String queryCondition, String userOpenId) {
		List<Order> orders = new ArrayList<Order>();
		if (queryCondition == null || queryCondition.equals("")) {
			List<Order> queryOrders = selectList(
					new EntityWrapper<Order>().where("userId= {0}", userOpenId).and("hasDelete=0"));
			queryOrders.forEach(order -> {
				orders.add(detail(order));
			});
		} else {
			List<Order> queryOrders = selectList(
					new EntityWrapper<Order>().where("userId= {0}", userOpenId).and("hasDelete=0").and(queryCondition));
			queryOrders.forEach(order -> {
				orders.add(detail(order));
			});
		}
		return orders;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.kakahair.plat.service.OrderService#place(java.math.BigDecimal,
	 * java.util.List, java.lang.Integer, java.util.Date, java.lang.String,
	 * java.lang.Integer)
	 */
	@Override
	public Order place(HttpServletRequest request, BigDecimal allPrice, List<String> servicesId, Integer technicianId,
			Date appointDate, String userId, Integer shopId, String phoneNum, String technicianName, String remark)
			throws Exception {
		WxPayService wxService = new WxPayServiceImpl();
		Shop shop = shopService.selectById(shopId);
		Order newOrder = new Order().setId(Utility.generateNumString(10)).setAllPrice(allPrice)
				.setServicesId(servicesId.toArray(new String[servicesId.size()])).setTechnicianId(technicianId)
				.setAppointDate(appointDate).setUserId(userId).setShopId(shopId).setImg(shop.getAvatar())
				.setShopUserId(shopService.selectById(shopId).getMasterId()).setTitle(shop.getTitle())
				.setPhoneNum(phoneNum).setTechnicianName(technicianName).setRemark(remark).setHasDelete(true);
		this.detail(newOrder);
		WxPayUnifiedOrderRequest req = new WxPayUnifiedOrderRequest();
		List<String> serviceNames = new ArrayList<String>();
		newOrder.getService().forEach(service -> {
			serviceNames.add(service.getName());
		});
		req.setBody(newOrder.getTitle() + "-" + serviceNames.toString());
		req.setOutTradeNo(newOrder.getId());
		req.setOpenid(userId);
		req.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(newOrder.getAllPrice().toString()));
		req.setSpbillCreateIp(request.getLocalAddr());
		wxService.setConfig(config);
		WxPayMpOrderResult wxOrder = wxService.createOrder(req);
		this.insert(newOrder);
		newOrder.setWxOrder(wxOrder);
		return newOrder;
	}

}
